﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CNCSoft.EData;
using System.Data.SqlClient;
using Common;

namespace CNCSoft.ErpApps.TMS.Academic
{
    public partial class frmDiemThi_New : Form
    {
        #region(Biến toàn cục)
        DataSet _ds;
        string _strCon;
        DataRelation _master_detail;
        #endregion

        public frmDiemThi_New()
        {
            InitializeComponent();
            _strCon = GlobalVariable.WSInfo.ConnectionString;
            _ds = new DataSet();
        }

        private void frmDiemDanh_New_Load(object sender, EventArgs e)
        {
            try
            {
                //init for dataset
                _ds.Tables.Add("LOP_READY");
                _ds.Tables.Add("GIAOVIEN_READY");
                _ds.Tables.Add("CANBOCOITHI");
                _ds.Tables.Add("HINHTHUCKIEMTRA");

                _ds.Tables.Add("MASTER");
                _ds.Tables.Add("DETAIL");

                //call method load LOP => Gan DM_LOP ready cho LookupEdit
                this.LoadLopByTrangThai();

                //Lod cac DM phuc vu cho cac cot Lookup
                LoadCacDanhMuc_Lookup();

                gvGiaoVien.IndicatorWidth = 40;  //Kich thuoc tieu de hang
                gvHocSinh.IndicatorWidth = 40;  //Kich thuoc tieu de hang

                colNgayThi.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void GetDataByLop(string MaLop)
        {
            SqlConnection cnn = new SqlConnection(_strCon);

            try
            {
                if (_ds.Tables["DETAIL"] != null)
                {
                    _ds.Tables["DETAIL"].Clear();
                }
                if (_ds.Tables["MASTER"] != null)
                {
                    _ds.Tables["MASTER"].Clear();
                }

                //mapping data to MASTER
                SqlParameter[] sqlP_MaLop = new SqlParameter[1];
                sqlP_MaLop[0] = new SqlParameter("@MaKhoaHoc", MaLop);
                SQLHelper.Fill(_ds.Tables["MASTER"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_frmDiemThi_GetDataStartUp]", sqlP_MaLop);
                
                //mapping data to DETAIL
                SqlParameter[] sqlP_D = new SqlParameter[1];
                sqlP_D[0] = new SqlParameter("@MaKhoaHoc", MaLop);
                SQLHelper.Fill(_ds.Tables["DETAIL"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_frmDiemThi_GetHocSinhByLop]", sqlP_D);
                _ds.Tables["DETAIL"].Columns["ID"].AutoIncrement = true;
                _ds.Tables["DETAIL"].Columns["ID"].AutoIncrementStep = 1;

                if (_ds.Tables["DETAIL"].Columns.IndexOf("DiemTrungBinh")<0)
                {
                    _ds.Tables["DETAIL"].Columns.Add("DiemTrungBinh").Expression = "IIF( (iif(DiemNghe is null, 0, 1) + iif(DiemNoi is null, 0, 1) + iif(DiemDoc is null, 0, 1) +  iif(DiemViet is null, 0, 1) + iif(DiemNguPhap is null, 0, 1) ) = 0, " +
                                                                               "null, " +
                                                                               "( isnull(DiemNghe, 0) + isnull(DiemNoi, 0) + isnull(DiemDoc, 0) + isnull(DiemViet, 0) + isnull(DiemNguPhap, 0) ) " +
                                                                               "/" +
                                                                               "( iif(DiemNghe is null, 0, 1) + iif(DiemNoi is null, 0, 1) + iif(DiemDoc is null, 0, 1) +  iif(DiemViet is null, 0, 1) + iif(DiemNguPhap is null, 0, 1) ) " +
                                                                               ")";
                }
                //catch { };

                //SET PRIMARY KEY
                _ds.Tables["MASTER"].PrimaryKey = new DataColumn[] { _ds.Tables["MASTER"].Columns["MaHocTap"] };
                _ds.Tables["DETAIL"].PrimaryKey = new DataColumn[] { _ds.Tables["DETAIL"].Columns["ID"] };

                //SET RELATIONSHIP
                if (_ds.Relations.Count == 0)
                    _master_detail = _ds.Relations.Add("M_D", _ds.Tables["MASTER"].Columns["MaHocTap"], _ds.Tables["DETAIL"].Columns["MaHocTap"]);

                //bind for grid MASTER
                gcGiaoVien.DataSource = _ds;
                gcGiaoVien.DataMember = "MASTER";

                //bind data to gridcontrol HOCSINH
                gcHocSinh.DataSource = _ds;
                gcHocSinh.DataMember = "MASTER.M_D";
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        //method load LOP ready
        private void LoadLopByTrangThai() 
        {
            //clear data before bind data 
            if (_ds.Tables["LOP_READY"] != null)
            {
                _ds.Tables["LOP_READY"].Clear();
            }

            try
            {
                //mapping data to DATASET
                SqlParameter[] sqlP = new SqlParameter[1];
                sqlP[0] = new SqlParameter("@TrangThai", "Ready");
                SQLHelper.Fill(_ds.Tables["LOP_READY"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_LoadLopByTrangThai]", sqlP);
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message);
            }

            //bind data to control
            cboKhoaHoc.Properties.DataSource = _ds.Tables["LOP_READY"];
            cboKhoaHoc.Properties.DisplayMember = "TenKhoaHoc";
            cboKhoaHoc.Properties.ValueMember = "MaKhoaHoc";
        }

        private void LoadCacDanhMuc_Lookup()
        {
            //DataTable dtDMHTKT = new DataTable();
            try
            {
                //Danh muc HINHTHUCKIEMTRA_NN
                //clear data before bind data 
                if (_ds.Tables["HINHTHUCKIEMTRA"] != null)
                {
                    _ds.Tables["HINHTHUCKIEMTRA"].Clear();
                }

                SQLHelper.Fill(_ds.Tables["HINHTHUCKIEMTRA"], _strCon, "SELECT * FROM DM_HINHTHUCKIEMTRA_NN");
                repositoryItemLookUpEdit_HinhThucKiemTra_NN.DataSource = _ds.Tables["HINHTHUCKIEMTRA"];
                repositoryItemLookUpEdit_HinhThucKiemTra_NN.DisplayMember = "MaHinhThucKiemTra_NN";
                repositoryItemLookUpEdit_HinhThucKiemTra_NN.ValueMember = "MaHinhThucKiemTra_NN";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        //method load GIAOVIEN READY BY LOP
        private void LoadGiaoVienByLop(string malop)
        {       
                //clear data before bind data 
            if (_ds.Tables["GIAOVIEN_READY"] != null)
            {
                _ds.Tables["GIAOVIEN_READY"].Clear();
            }

            try
            {
                //mapping data to DATASET
                SqlParameter[] sqlP = new SqlParameter[1];
                sqlP[0] = new SqlParameter("@MaKhoaHoc", malop);
                SQLHelper.Fill(_ds.Tables["GIAOVIEN_READY"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_LoadGiaoVienByLop]", sqlP);
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message);
            }

            //bind data to control
            repIGiaoVien.DataSource = _ds.Tables["GIAOVIEN_READY"];
            repIGiaoVien.DisplayMember = "TenGiaoVien";
            repIGiaoVien.ValueMember = "MaGiaoVien";
        }

        private void LoadCBoCoiThi() {
            //clear data before bind data 
            if (_ds.Tables["CANBOCOITHI"] != null)
            {
                _ds.Tables["CANBOCOITHI"].Clear();
            }

            try
            {
                //mapping data to DATASET
                SQLHelper.Fill(_ds.Tables["CANBOCOITHI"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_frmDiemThi_GetCanBoCoiThi]");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //bind data to control
            repICBoCoiThi.DataSource = _ds.Tables["CANBOCOITHI"];
            repICBoCoiThi.DisplayMember = "FullName";
            repICBoCoiThi.ValueMember = "UserID";
        }

        //method execute query into MASTER
        private Boolean ExecuteIntoMaster() 
        {
            //Declare param and assign value
            SqlParameter[] pInsert = new SqlParameter[9];
            SqlParameter[] pUpdate = new SqlParameter[9];
            SqlParameter[] pDelete = new SqlParameter[1];

            //tham so cho sp INSERT
            pInsert[0] = new SqlParameter("@MaHocTap", SqlDbType.UniqueIdentifier, 18, "MaHocTap");
            pInsert[1] = new SqlParameter("@MaKhoaHoc", SqlDbType.VarChar, 20, "MaKhoaHoc");
            pInsert[2] = new SqlParameter("@MaCanBoCoiThi1", SqlDbType.VarChar, 20, "MaCanBoCoiThi1");
            pInsert[3] = new SqlParameter("@MaCanBoCoiThi2", SqlDbType.VarChar, 20, "MaCanBoCoiThi2");
            pInsert[4] = new SqlParameter("@MaGiaoVienChamThi", SqlDbType.VarChar, 20, "MaGiaoVienChamThi");
            pInsert[5] = new SqlParameter("@NgayThi", SqlDbType.Date, 10, "NgayThi");
            pInsert[6] = new SqlParameter("@SoGioThi", SqlDbType.Decimal, 18, "SoGioThi");
            pInsert[7] = new SqlParameter("@NhanXet", SqlDbType.NVarChar, 200, "NhanXet");
            pInsert[8] = new SqlParameter("@MaHinhThucKiemTra_NN", SqlDbType.VarChar, 10, "MaHinhThucKiemTra_NN");

            //tham so cho sp UPDATE
            pUpdate[0] = new SqlParameter("@MaKhoaHoc", SqlDbType.VarChar, 20, "MaKhoaHoc");
            pUpdate[1] = new SqlParameter("@MaCanBoCoiThi1", SqlDbType.VarChar, 20, "MaCanBoCoiThi1");
            pUpdate[2] = new SqlParameter("@MaCanBoCoiThi2", SqlDbType.VarChar, 20, "MaCanBoCoiThi2");
            pUpdate[3] = new SqlParameter("@MaGiaoVienChamThi", SqlDbType.VarChar, 20, "MaGiaoVienChamThi");
            pUpdate[4] = new SqlParameter("@NgayThi", SqlDbType.Date, 10, "NgayThi");
            pUpdate[5] = new SqlParameter("@SoGioThi", SqlDbType.Decimal, 18, "SoGioThi");
            pUpdate[6] = new SqlParameter("@NhanXet", SqlDbType.NVarChar, 200, "NhanXet");
            pUpdate[7] = new SqlParameter("@MaHocTap", SqlDbType.UniqueIdentifier, 18, "MaHocTap");
            pUpdate[8] = new SqlParameter("@MaHinhThucKiemTra_NN", SqlDbType.VarChar, 10, "MaHinhThucKiemTra_NN");

            //tham so cho sp DELETE
            pDelete[0] = new SqlParameter("@MaHocTap", SqlDbType.UniqueIdentifier, 18, "MaHocTap");

            //assign all sp into all cmd
            SqlConnection cnn = new SqlConnection(_strCon);

            SqlCommand cmdInsert = new SqlCommand();
            cmdInsert.Connection = cnn;
            cmdInsert.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_Insert]";
            cmdInsert.CommandType = CommandType.StoredProcedure;

            SqlCommand cmdUpdate = new SqlCommand();
            cmdUpdate.Connection = cnn;
            cmdUpdate.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_Update]";
            cmdUpdate.CommandType = CommandType.StoredProcedure;

            SqlCommand cmdDelete = new SqlCommand();
            cmdDelete.Connection = cnn;
            cmdDelete.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_Delete]";
            cmdDelete.CommandType = CommandType.StoredProcedure;

            // Add the parameter to the Parameters collection.
            cmdInsert.Parameters.AddRange(pInsert);
            cmdUpdate.Parameters.AddRange(pUpdate);
            cmdDelete.Parameters.AddRange(pDelete);

            SqlDataAdapter da = new SqlDataAdapter();
            da.InsertCommand = cmdInsert;
            da.UpdateCommand = cmdUpdate;
            da.DeleteCommand = cmdDelete;

            //Update
            try
            {
                da.Update(_ds, "MASTER");
                _ds.Tables["MASTER"].AcceptChanges();
                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            
        }

        //method execute query into DETAIL
        private Boolean ExecuteIntoDetail() 
        {
            //Declare param and assign value
            SqlParameter[] pInsert = new SqlParameter[9];
            SqlParameter[] pUpdate = new SqlParameter[9];
            SqlParameter[] pDelete = new SqlParameter[1];

            //tham so cho sp INSERT
            pInsert[0] = new SqlParameter("@MaHocTap", SqlDbType.UniqueIdentifier, 18 ,"MaHocTap");
            pInsert[1] = new SqlParameter("@InvoiceNumber", SqlDbType.VarChar, 12, "InvoiceNumber");
            pInsert[2] = new SqlParameter("@DiemNghe", SqlDbType.Decimal, 18, "DiemNghe");
            pInsert[3] = new SqlParameter("@DiemNoi", SqlDbType.Decimal, 18, "DiemNoi");
            pInsert[4] = new SqlParameter("@DiemDoc", SqlDbType.Decimal, 18, "DiemDoc");
            pInsert[5] = new SqlParameter("@DiemViet", SqlDbType.Decimal, 18, "DiemViet");
            pInsert[6] = new SqlParameter("@DiemNguPhap", SqlDbType.Decimal, 18, "DiemNguPhap");
            pInsert[7] = new SqlParameter("@GhiChu", SqlDbType.NVarChar, 200, "GhiChu");
            //Dien hinh cua cách Insert tablse có field ID va sau khi Insert thì ID của Datatable được map (trùng) với ID của database.
            // 1. Trong sp_... phải có tham số ID là OUTPUT  (@ID int output)
            // 2. Cuối sp_... phải SET @ID = SCOPE_IDENTITY()
            // 3. Trong C# dung parameter có Dicrection là OUTPUT
            pInsert[8] = new SqlParameter("@ID",SqlDbType.Int,18,"ID");
            pInsert[8].Direction = ParameterDirection.Output;

            //tham so cho sp UPDATE
            pUpdate[0] = new SqlParameter("@MaHocTap", SqlDbType.UniqueIdentifier, 18, "MaHocTap");
            pUpdate[1] = new SqlParameter("@InvoiceNumber", SqlDbType.VarChar, 12, "InvoiceNumber");
            pUpdate[2] = new SqlParameter("@DiemNghe", SqlDbType.Decimal, 18, "DiemNghe");
            pUpdate[3] = new SqlParameter("@DiemNoi", SqlDbType.Decimal, 18, "DiemNoi");
            pUpdate[4] = new SqlParameter("@DiemDoc", SqlDbType.Decimal, 18, "DiemDoc");
            pUpdate[5] = new SqlParameter("@DiemViet", SqlDbType.Decimal, 18, "DiemViet");
            pUpdate[6] = new SqlParameter("@DiemNguPhap", SqlDbType.Decimal, 18, "DiemNguPhap");
            pUpdate[7] = new SqlParameter("@GhiChu", SqlDbType.NVarChar, 200, "GhiChu");
            pUpdate[8] = new SqlParameter("@ID", SqlDbType.Int, 18, "ID");
           

            //tham so cho sp DELETE
            pDelete[0] = new SqlParameter("@ID", SqlDbType.Int, 18, "ID");

            //assign all sp into all cmd
            SqlConnection cnn = new SqlConnection(_strCon);

            SqlCommand cmdInsert = new SqlCommand();
            cmdInsert.Connection = cnn;
            cmdInsert.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_ChiTiet_Insert]";
            cmdInsert.CommandType = CommandType.StoredProcedure;
            
            SqlCommand cmdUpdate = new SqlCommand();
            cmdUpdate.Connection = cnn;
            cmdUpdate.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_ChiTiet_Update]";
            cmdUpdate.CommandType = CommandType.StoredProcedure;

            SqlCommand cmdDelete = new SqlCommand();
            cmdDelete.Connection = cnn;
            cmdDelete.CommandText = "[dbo].[sp_Invoice_KhoaHoc_KQHT_ChiTiet_Delete]";
            cmdDelete.CommandType = CommandType.StoredProcedure;

            // Add the parameter to the Parameters collection.
            cmdInsert.Parameters.AddRange(pInsert);
            cmdUpdate.Parameters.AddRange(pUpdate);
            cmdDelete.Parameters.AddRange(pDelete);

            //execute all cmd
            SqlDataAdapter da = new SqlDataAdapter();
            da.InsertCommand = cmdInsert;
            da.UpdateCommand = cmdUpdate;
            da.DeleteCommand = cmdDelete;

            //Update
            try
            {
                da.Update(_ds, "DETAIL");
                _ds.Tables["DETAIL"].AcceptChanges();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
           
        }

        private void cmdCapNhat_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.ExecuteIntoMaster())
                    this.ExecuteIntoDetail();

                //mapping data to DETAIL
                //SqlParameter[] sqlP_D = new SqlParameter[1];
                //sqlP_D[0] = new SqlParameter("@MaKhoaHoc", cboKhoaHoc.EditValue.ToString());
                //SQLHelper.Fill(_ds.Tables["DETAIL"], _strCon, CommandType.StoredProcedure, "[dbo].[sp_frmDiemThi_GetHocSinhByLop]", sqlP_D);

                //gvHocSinh.MoveFirst();

                cboKhoaHoc.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void cmdBoQua_Click(object sender, EventArgs e)
        {
            //refesh dataset
            _ds.RejectChanges();

            //call method load data startup by malop
            //GetDataByLop(cboKhoaHoc.EditValue.ToString());
            cboKhoaHoc.Enabled = true;
        }

        private void cboKhoaHoc_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                //assgin value for cell GiaoVien
                this.LoadGiaoVienByLop(cboKhoaHoc.EditValue.ToString().Trim());  //Chi la gan DM
                
                //load can bo coi thi
                this.LoadCBoCoiThi();

                //GetData
                this.GetDataByLop(cboKhoaHoc.EditValue.ToString().Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

       
        private void gcGiaoVien_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
                {
                    //    NotifyUser(); // optionally

                    try
                    {
                        //Ma lop
                        string MaLop = cboKhoaHoc.EditValue.ToString();
                        //assign value for cell MaHocTap
                        Guid NewMaHocTap = Guid.NewGuid();

                        DataRow M_NewRow = _ds.Tables["MASTER"].NewRow();
                        M_NewRow["MaHocTap"] = NewMaHocTap;
                        M_NewRow["MaKhoaHoc"] = MaLop;
                        M_NewRow["NgayThi"] = GlobalVariable.WSInfo.WorkingDate ;
                        M_NewRow["SoGioThi"] = Convert.ToDecimal(SQLHelper.ExecuteScalar(_strCon, "SELECT CASE WHEN isnull(SoNgayHoc,0) = 0 THEN null ELSE round(convert(float, SoGioHoc)/SoNgayHoc,1) END  FROM DM_KHOAHOC WHERE MaKhoaHoc = '" + MaLop + "'"));
                        _ds.Tables["MASTER"].Rows.Add(M_NewRow);

                        //Dua danh sach hoc sinh cua lop va datatable DETAIL
                        DataTable dt = new DataTable();
                        SQLHelper.Fill(dt, _strCon, "SELECT Invoice_KhoaHoc.InvoiceNumber, Holot, Ten " +
                                                    "FROM Invoice_KhoaHoc " +
                                                    "JOIN Invoice ON Invoice_KhoaHoc.InvoiceNumber = Invoice.InvoiceNumber " +
                                                    "JOIN Enquiry ON Invoice.EnquiryNumber = Enquiry.EnquiryNumber  " +
                                                    "WHERE MaKhoaHoc = '" + MaLop + "'");
                        foreach (DataRow dr in dt.Rows)
                        {
                            DataRow DetailNewRow = _ds.Tables["DETAIL"].NewRow();
                            DetailNewRow["MaHocTap"] = NewMaHocTap;
                            DetailNewRow["InvoiceNumber"] = dr["InvoiceNumber"];
                            DetailNewRow["HoLot"] = dr["HoLot"];
                            DetailNewRow["Ten"] = dr["Ten"];
                            //DetailNewRow["DiemTrungBinh"] = 0.0;
                            _ds.Tables["DETAIL"].Rows.Add(DetailNewRow);
                        }

                        gcHocSinh.RefreshDataSource();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    e.Handled = true; // this line prevents adding a row

                    cboKhoaHoc.Enabled = false; //Khoa, khi nao luu moi mo lai de diem danh lop khac

            }
        }

        private void gvGiaoVien_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle > -1)
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void gvHocSinh_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle > -1)
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void gvHocSinh_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (e.Value == null || e.Value.ToString() == "")
            {
                e.Value = null;
                return;
            }

            if (gvHocSinh.FocusedColumn.FieldName.Substring(0, 4).ToUpper() == "DIEM")
            {
                try
                {
                    Double val = Convert.ToDouble(e.Value);
                    if (val > 20 || val < 0)
                    {
                        e.Valid = false;
                        e.ErrorText = "Điểm không hợp lệ. ";
                        return;
                    }
                    //if (val > 10)
                    //{
                    //    //Chia cho 10 de thuan tien cho viec nhap lieu (ko can dau phay)
                    //    e.Value = Convert.ToDecimal(e.Value) / 10;
                    //}

                }
                catch
                {
                }
            }
        }

        private void gvGiaoVien_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            //CHi xu ly cho TH cot so lieu la "MaHinhthucKiemTra_NN"
            if (gvGiaoVien.FocusedColumn.FieldName.ToUpper() == "MaHinhthucKiemTra_NN".ToUpper())
            {
                BindingManagerBase bmb = this.BindingContext[_ds, "MASTER"];

                //Lay do lan thi toi da cua 1 ky thi (hinh thuc kiem tra)
                int intSoLanThiToiDa = Convert.ToInt16(SQLHelper.ExecuteScalar(_strCon, "SELECT SoLanThiToiDa FROM DM_HINHTHUCKIEMTRA_NN WHERE MaHinhThucKiemTra_NN = '" + e.Value.ToString() + "'"));
                
                if (intSoLanThiToiDa == 0) return;  //Khong valid gi het, muon chon gi chon (vd TH OTHER)

                int intSoLanDaThi = 0;
                foreach (DataRow dr in _ds.Tables["MASTER"].Rows)
                {
                    if (dr != _ds.Tables["MASTER"].Rows[bmb.Position]) //Chi nghien cuu may row khong phai row hien hanh
                    {
                        if (e.Value.ToString() == dr["MaHinhthucKiemTra_NN"].ToString())
                            intSoLanDaThi ++ ;
                    }
                }

                if (intSoLanDaThi >= intSoLanThiToiDa)
                {
                    e.Valid = false;
                    e.ErrorText = e.Value.ToString() +  " chỉ kiểm tra " + intSoLanThiToiDa.ToString("N0") +  " lần.";
                    return;
                }

            }
        }
       

   
    
    }//the end class
}//the end namespace
